package com.laiyonghao
{
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.getTimer;

public class Uuid
{
  // Char codes for 0123456789ABCDEF
  private static const ALPHA_CHAR_CODES:Array = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70];

  private var _byteArray:ByteArray; //The byte array representation of this UUID
  private var _string:String; //The text representation of the UUID

  public function Uuid()
  {
    generate();
  }

  public function generate():Uuid
  {
    _string = null;
    var r:uint = uint(new Date().time);
    trace("Date time uint: " + r);
    _byteArray = new ByteArray();
    trace("Total memory hash: " + System.totalMemory ^ r);
    _byteArray.writeUnsignedInt(System.totalMemory ^ r);
    _byteArray.writeInt(getTimer() ^ r);
    _byteArray.writeDouble(Math.random() * r);
    return this;
  }

  public function readByteArray(ba:ByteArray):void
  {
    _byteArray.position = 0;
    _byteArray.readBytes(ba);
  }

  public function get byteArray():ByteArray
  {
    return _byteArray;
  }

  public function toString():String
  {
    if (_string)
    {
      return _string
    }
    _byteArray.position = 0;
    var chars:Array = new Array(36);
    var index:uint = 0;
    for (var i:uint = 0; i < 16; i++)
    {
      if (i == 4 || i == 6 || i == 8 || i == 10)
      {
        chars[index++] = 45; // Hyphen char code
      }
      var b:int = _byteArray.readByte();
      chars[index++] = ALPHA_CHAR_CODES[(b & 0xF0) >>> 4];
      chars[index++] = ALPHA_CHAR_CODES[(b & 0x0F)];
    }
    _string = String.fromCharCode.apply(null, chars);
    return _string;
  }
}
}